<template>
  <div class="container">
    <div class="container-filter">
      <div class="container-filter-left">
        <el-input
          pre-icon="search"
          v-model="state.searchKeyword"
          placeholder="请输入关键词"
          clearable
          @clear="getTableList(state.page, state.pageSize)"
        >
          <template #append>
            <el-button @click="searchBtn" icon="Search" />
          </template>
        </el-input>
        <el-checkbox style="margin-left: 15px">收藏</el-checkbox>
      </div>
      <div class="container-filter-right">
        <el-button icon="plus" @click="handleDialog('情报上传')" type="primary">文件上传</el-button>
      </div>
    </div>
    <div class="container-content">
      <el-table border :data="state.list" align-center :row-class-name="tableRowClassName">
        <el-table-column prop="prop1" width="70" label="序号">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="文件名" />
        <el-table-column prop="theme" label="主题" />
        <!-- <el-table-column prop="author" label="作者" /> -->
        <el-table-column prop="keyword" label="关键词" />
        <el-table-column prop="targ" label="标签">
          <template #default="scope">
            <el-tag type="warning">
              {{ scope.row.targ }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收藏">
          <template #default="scope">
            <SvgIcon
              @click="scope.row.collect = !scope.row.collect"
              style="cursor: pointer"
              :name="scope.row.collect ? 'sc-fulled' : 'sc-empty'"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
              {{ scope.row.status == 1 ? "已训练" : "待训练" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button type="primary" text @click="upTag(scope.row)">标签修改</el-button>
            <el-button @click="handleDialog('原文', scope.row)" text type="warning"> 原文 </el-button>
            <el-button @click="handleDialog('关系图谱', scope.row)" text type="success"> 关系图谱 </el-button>
            <el-button @click="handleDel(scope.row._id)" text type="danger"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px">
        <el-pagination
          background
          layout="total,  prev, pager, next"
          :total="state.total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!--NOTE(@date:2023-12-14 11:56:36 谭人杰): 弹窗-->
    <el-dialog
      @opened="handleDialogOpened"
      v-model="state.dialog_conf.visiable"
      :title="state.dialog_conf.title"
      :destroy-on-close="state.dialog_conf.isDestory"
      :draggable="state.dialog_conf.draggable"
      :close-on-click-modal="state.dialog_conf.closeOnClickModal"
      :width="['原文', '翻译', '关系图谱'].some((e) => e == state.dialog_conf.title) ? '1100px' : '600px'"
    >
      <el-form label-width="120" inline v-if="state.dialog_conf.title == '情报上传'">
        <el-form-item class="must-fill" label="标签">
          <el-select v-model="state.form.targ" class="m-2" placeholder="选择标签" size="large">
            <el-option v-for="(item, index) in state.options" :key="index" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item class="must-fill" label="是否需要解压">
          <el-radio-group>
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item class="must-fill" label="资料上传">
          <el-upload
            class="upload-demo"
            action="http://mapcan.top:11305/v1.0/upload"
            :on-success="handleSuccess"
            multiple
            :limit="1"
            :file-list="state.fileList"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-form v-else-if="state.dialog_conf.title == '标签修改'">
        <el-form-item class="must-fill" label="标签">
          <el-select v-model="state.form.targ" class="m-2" placeholder="选择标签" size="large">
            <el-option v-for="(item, index) in state.options" :key="index" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-row v-else-if="state.dialog_conf.title == '原文' || state.dialog_conf.title == '翻译'" :gutter="49">
        <el-col style="display: flex; justify-content: flex-end">
          <el-dropdown trigger="click" @command="handleCommand">
            <el-button text type="warning">
              翻译<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="item in state.opt_conf.lan_opt" :command="item.value" :key="item.value">
                  {{ item.value }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
        <el-col :span="state.dialog_conf.title == '翻译' ? 12 : 24">
          <div class="fy_title">
            {{ state.form_data.left_title }}
          </div>
          <vue-office-docx :src="state.docx" @error="errorHandler" @rendered="rendered" style="height: 600px" />
          <!-- <div
            style="
              height: 600px;
              overflow-y: scroll;
              overflow-x: hidden;
              width: 100%;
              border: 1px solid var(--el-border-color);
              word-wrap: break-word;
              padding: 10px;
            "
          >
            {{ state.form_data.old_text }}
          </div> -->
        </el-col>
        <el-col v-if="state.dialog_conf.title == '翻译'" :span="12">
          <div class="fy_title">
            <span style="--un-animation-delay: 0.6s" class="animate-jump">
              {{ state.form_data.right_title }}
            </span>
          </div>
          <TypeWriter height="600px" style="border: 1px solid var(--el-border-color)" :text="state.form_data.text" />
        </el-col>
      </el-row>
      <el-row style="height: 80vh" v-else-if="state.dialog_conf.title == '关系图谱'">
        <RelationGraph
          ref="$relationGraph"
          :options="state.opt_conf.graphOptions"
          :on-node-click="onNodeClick"
          :on-line-click="onLineClick"
        />
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialog_conf.visiable = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import RelationGraph from "relation-graph/vue3"
import { ElMessage, ElMessageBox } from "element-plus"
import { getRandomChineseWord, getRandomString, lan_opt } from "@/utils/mock-data/index.js"
import { reactive, onMounted, ref, nextTick } from "vue"
import TypeWriter from "@/components/TypeWriter/index.vue"
import { getData, searchData, delData, createData, updateData } from "@/api/information/index"
import { searchAll } from "@/api/tags/index"
//引入VueOfficeDocx组件
import VueOfficeDocx from "@vue-office/docx"
//引入相关样式
import "@vue-office/docx/lib/index.css"
const $relationGraph = ref<RelationGraph>(null)
const state = reactive({
  list: [],
  upId: "",
  docx: "",
  page: 1,
  pageSize: 10,
  total: 0,
  searchKeyword: "",
  options: [{ name: "", desc: "" }],
  fileList: [],
  form: {
    name: "",
    theme: "",
    author: "",
    keyword: "",
    targ: "",
    collect: false,
    files: {},
    status: 0
  },
  dialog_conf: {
    visiable: false,
    title: "",
    isDestory: false, //关闭前销毁
    draggable: true, //拖拽
    closeOnClickModal: false
  },
  opt_conf: {
    lan_opt: lan_opt?.[0]?.children ?? [],
    graphOptions: {
      allowSwitchLineShape: true,
      allowSwitchJunctionPoint: true,
      defaultJunctionPoint: "border"
    }
  },
  form_data: {
    left_title: "",
    right_title: "",
    old_text: "",
    text: ""
  }
})

// NOTE(@date:2024-1-3 16:34:36 陈谦): 接口调用
const getTableList = (page: number, pageSize: number) => {
  getData(page, pageSize)
    .then((res: any) => {
      if (res.code == 200) {
        state.list = res.data.list
        state.total = res.data.total
      }
    })
    .catch((err: any) => {
      console.log(err)
    })
}

const getOptions = () => {
  searchAll().then((res: any) => {
    if (res.code == 200) {
      state.options = res.data
      console.log(state.options)
    }
  })
}

const handleCurrentChange = (val: any) => {
  state.page = val
  getTableList(val, state.pageSize)
}
const searchBtn = () => {
  searchData("keyword", state.searchKeyword).then((res: any) => {
    if (res.code == 200) {
      state.list = res.data
    }
  })
}
const handleDel = (id: any) => {
  delData(id).then((res: any) => {
    ElMessageBox.confirm("确认删除数据吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      if (res.code == 200) {
        getTableList(state.page, state.pageSize)
        ElMessage({
          type: "success",
          message: `操作成功`
        })
      }
    })
  })
}

const handleSuccess = (res: any) => {
  if (res.code == 200) {
    state.form.files = res.data
    state.form.name = res.data.fileName
  }
}

const submit = () => {
  const { title } = state.dialog_conf
  if (title == "标签修改") {
    upData()
  } else {
    addData()
  }
}

const upData = () => {
  updateData(state.upId, state.form).then((res: any) => {
    if (res.code == 200) {
      getTableList(state.page, state.pageSize)
      state.dialog_conf.visiable = false
      ElMessage({
        type: "success",
        message: `操作成功`
      })
    }
  })
}

const addData = () => {
  const data = {
    ...state.form,
    name: state.form.name.split("_")[0]
  }
  createData(data).then((res: any) => {
    if (res.code == 200) {
      getTableList(state.page, state.pageSize)
      state.dialog_conf.visiable = false
      state.form = {
        name: "",
        theme: "",
        author: "",
        keyword: "",
        targ: "",
        collect: false,
        files: {},
        status: 0
      }
      state.fileList = []
      ElMessage({
        type: "success",
        message: `操作成功`
      })
    }
  })
}

const handleDialog = (title: string, item: any) => {
  state.dialog_conf.visiable = true
  state.dialog_conf.title = title
  if (title == "原文") {
    state.docx = "http://mapcan.top:11305" + item.files[0].relPath
  }
}

const rendered = (v: any) => {
  console.log("渲染成功", v)
}
const errorHandler = (err: any) => {
  console.log("渲染失败", err)
}

const upTag = (val: any) => {
  state.dialog_conf.visiable = true
  state.dialog_conf.title = "标签修改"
  state.form = val
  state.upId = val._id
  searchData("targ", val.targ).then((res: any) => {
    if (res.code == 200) {
      if (res.data.length > 0) state.form.targ = res.data[0].targ
    }
  })
}

const handleCommand = (v: string) => {
  state.dialog_conf.title = "翻译"
  state.form_data.text = getRandomChineseWord(100)
  state.form_data.old_text = getRandomString(1000)
  state.form_data.left_title = v?.split("译")?.[0] ?? ""
  state.form_data.right_title = v?.split("译")?.[1] ?? ""
  state.dialog_conf.visiable = true
}

const tableRowClassName = (rowIndex: number) => {
  if (rowIndex % 2 != 0) {
    return "warning-row"
  } else {
    return "success-row"
  }
}

const handleDialogOpened = () => {
  //需要指定 节点参数和连接线的参数
  const __graph_json_data = {
    rootId: "a",
    nodes: [
      // node配置选项：http://relation-graph.com/#/docs/node
      // node支持通过插槽slot完全自定义，示例：http://relation-graph.com/#/demo/adv-slot
      { id: "a", text: "甲方1", borderColor: "yellow" },
      { id: "b", text: "甲方2", color: "#43a2f1", fontColor: "yellow" },
      { id: "c", text: "甲方3", nodeShape: 1, width: 80, height: 60 },
      { id: "e", text: "甲方4", nodeShape: 0, width: 150, height: 150 }
    ],
    lines: [
      // link配置选项：http://relation-graph.com/#/docs/link
      { from: "a", to: "b", text: "关系1", color: "#43a2f1" },
      { from: "a", to: "c", text: "关系2" },
      { from: "a", to: "e", text: "关系3" },
      { from: "b", to: "e", color: "#67C23A" }
    ]
  }
  nextTick(() => {
    $relationGraph.value.setJsonData(__graph_json_data)
  })
}

const onNodeClick = (nodeObject: any, $event: any) => {
  console.log("onNodeClick:", nodeObject)
}
const onLineClick = (linkObject: any, $event: any) => {
  console.log("onLineClick:", linkObject)
}

onMounted(() => {
  getTableList(state.page, state.pageSize)
  getOptions()
})
</script>

<style lang="scss" scoped>
.fy_title {
  margin-bottom: 15px;
  width: 100%;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}
.input {
  :deep(.el-textarea__inner) {
    height: 700px !important;
  }
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
